// cloudfunctions/createPost/index.js
const cloud = require('wx-server-sdk');
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
  })
const db = cloud.database();

exports.main = async (event, context) => {
    try {
        const { title, content, images, productRelations,userInfo } = event;
        console.log(userInfo);
        if (!title || !images || images.length === 0 || !productRelations || productRelations.length === 0) {
          return { success: false, message: '缺少必要参数' };
        }
        
        // 验证产品关联数据格式
        const isValidProductRelations = productRelations.every(relation => {
          return relation.ipId && relation.ipName && relation.seriesId && 
                 relation.seriesName && relation.productId && relation.productName;
        });
        
        if (!isValidProductRelations) {
          return { success: false, message: '产品关联数据格式错误' };
        }
        
        // 保存帖子
        const result = await db.collection('community_posts').add({
          data: {
            userId: userInfo._id,
            userName: userInfo.nickName,
            userAvatar: userInfo.avatarUrl,
            title,
            content,
            images,
            productRelations,
            likeCount: 0,
            commentCount: 0,
            createTime: db.serverDate(),
            updateTime: db.serverDate(),
            status: 'normal'
          }
        });
        
        return {
          success: true,
          data: { postId: result._id },
          message: '创建帖子成功'
        };
      } catch (error) {
        console.error('创建帖子失败', error);
        return {
          success: false,
          message: error.message || '服务器错误',
          error: error.message
        };
      }
};